package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    WeChatProperties weChatProperties;
    private final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {
        //发送http请求,获取OpenId
        String openId = getOpenId(userLoginDTO.getCode());


        if(openId == null || openId==""){
            new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //成功登入则查看是否已注册，未注册自动注册
        User user = userMapper.getByOpenId(openId);

        if (user == null){
            user = User.builder().openid(openId).createTime(LocalDateTime.now()).build();

            userMapper.save(user);
        }


        return user;
    }

    /**
     * 获取Openid
     * @param code 授权码
     * @return
     */
    private String getOpenId(String code) {
        HashMap<String,String> params = new HashMap<>();
        params.put("appid", weChatProperties.getAppid());
        params.put("secret",weChatProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type","authorization_code");
        String response = HttpClientUtil.doGet(WX_LOGIN_URL, params);


        JSONObject json = JSON.parseObject(response);
        String openId = json.getString("openid");
        return openId;
    }
}
